const { searchRecord, updateRecord, getItems } = require('../../utils/feishuAPI');
Page({
  data: {
    goal: {},
    classGoal: '',
    organGoal: '',
    btnText: '修改目标',
    isEditing: false  // 是否处于编辑模式
  },

  onLoad: function(options) {
    const that = this;
    tt.getStorage({
      key: options.question,
      success(res) {
        if (res.data) {
          console.log('read data success')
          that.data.classGoal = res.data['课程目标']
          that.data.organGoal = res.data['组织目标']
          that.setData({
            goal: res.data,
            classGoal: res.data['课程目标'],
            organGoal: res.data['组织目标']
          });
        }
      },
    });

  },

  onShow: function (){
    const that = this
    console.log(`show class goal: ${that.data.classGoal}`)
    console.log(`show organ goal: ${that.data.organGoal}`)
    that.setData({
      classGoal: that.data.classGoal,
      organGoal: that.data.organGoal
    })
  },

  toggleEdit: function() {
    const that = this
    const app = getApp()
    if (this.data.isEditing) {
      // 确认修改：保存数据
      this.setData({
        btnText: '修改目标',
        isEditing: false
      });
      app.globalData.classGoal = that.data.classGoal
      app.globalData.organGoal = that.data.organGoal
      console.log(`current global class goal: ${app.globalData.classGoal}`)
      console.log(`current global organ goal: ${app.globalData.organGoal}`)
      const query = {
        filter: {
          "conjunction": "and",
          "conditions": [
            {
              "field_name": '周次',
              "operator": "is",
              "value": [
                app.globalData.week
              ]
            },
            {
              "field_name": '组号',
              "operator": "is",
              "value": [
                app.globalData.classInfo['组号']
              ]
            }
          ]
        }
      };
      searchRecord('目标管理表', query)
      .then((res) => {
        console.log(res)
        if (res != 0) {
          record_id = res.data.data.items[0].record_id
          console.log(`record_id: `, record_id)
          fields = {
            '课程目标': app.globalData.classGoal,
            '组织目标': app.globalData.organGoal
          }
          updateRecord('目标管理表', record_id, fields)
          .then((upres) => {
            if (upres != 0) {
              console.log(`update goal success`)
            } else {
              console.log(`update goal success else`)
            }
          })
        } else {
          console.log(`update goal failed`)
        }
      })
    } else {
      // 进入编辑模式
      this.setData({
        btnText: '确认修改',
        isEditing: true
      });
    }
  },

  onClassGoalInput: function(e) {
    this.setData({
      classGoal: e.detail.value
    });
  },

  onOrganGoalInput: function(e) {
    this.setData({
      organGoal: e.detail.value
    });
  }
});